import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import doctorService from '../services/doctorService';
import departmentService from '../services/departmentService';
import adminService from '../services/adminService';
import './AdminDoctorManagementPage.css';

const AdminDoctorManagementPage = () => {
    const [doctors, setDoctors] = useState([]);
    const [departments, setDepartments] = useState([]);
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [showModal, setShowModal] = useState(false);
    const [selectedDoctor, setSelectedDoctor] = useState(null);
    const [formData, setFormData] = useState({
        userId: '',
        specialization: '',
        departmentId: '',
        licenseNumber: '',
        bio: '',
        availableSlots: ''
    });
    
    const navigate = useNavigate();

    useEffect(() => {
        // 先加载科室和用户数据，再加载医生数据
        Promise.all([loadDepartments(), loadUsers()])
            .then(() => {
                return loadDoctors();
            })
            .catch(err => {
                setError('加载数据失败');
                console.error('加载数据失败:', err);
                setLoading(false);
            });
    }, []);

    const loadDoctors = () => {
        setLoading(true);
        return doctorService.getAllDoctors()
            .then(response => {
                // 这里检查response是否直接是数据还是包含data属性
                const doctorsData = Array.isArray(response) ? response : 
                                   (response && response.data ? response.data : []);
                setDoctors(doctorsData);
                setLoading(false);
                return response;
            })
            .catch(err => {
                setError('加载医生数据失败');
                console.error('加载医生数据失败:', err);
                setLoading(false);
                throw err;
            });
    };

    const loadDepartments = () => {
        return departmentService.getAllDepartments()
            .then(response => {
                // 这里检查response是否直接是数据还是包含data属性
                const deptData = Array.isArray(response) ? response : 
                               (response && response.data ? response.data : []);
                setDepartments(deptData);
                return response;
            })
            .catch(err => {
                console.error('加载科室数据失败:', err);
                setDepartments([]);
                throw err;
            });
    };

    const loadUsers = () => {
        return adminService.getAllUsers()
            .then(response => {
                // 这里检查response是否直接是数据还是包含data属性
                const usersData = Array.isArray(response) ? response : 
                                (response && response.data ? response.data : []);
                setUsers(usersData);
                return response;
            })
            .catch(err => {
                console.error('加载用户数据失败:', err);
                setUsers([]);
                throw err;
            });
    };

    const filterAvailableUsers = () => {
        if (!users || !Array.isArray(users) || !doctors || !Array.isArray(doctors)) {
            return [];
        }
        
        return users.filter(user => 
            !doctors.some(doctor => doctor && user && doctor.userId === user.id)
        );
    };

    const handleCreateDoctor = () => {
        setSelectedDoctor(null);
        setFormData({
            userId: '',
            specialization: '',
            departmentId: '',
            licenseNumber: '',
            bio: '',
            availableSlots: ''
        });
        setShowModal(true);
    };

    const handleEditDoctor = (doctor) => {
        setSelectedDoctor(doctor);
        setFormData({
            userId: doctor.userId,
            specialization: doctor.specialization || '',
            departmentId: doctor.departmentId || '',
            licenseNumber: doctor.licenseNumber || '',
            bio: doctor.bio || '',
            availableSlots: doctor.availableSlots || ''
        });
        setShowModal(true);
    };

    const handleDeleteDoctor = (id) => {
        if (window.confirm('确定要删除这位医生吗？')) {
            doctorService.deleteDoctor(id)
                .then(() => {
                    loadDoctors();
                })
                .catch(err => {
                    setError('删除医生失败');
                    console.error('删除医生失败:', err);
                });
        }
    };

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setFormData({
            ...formData,
            [name]: value
        });
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        
        if (selectedDoctor) {
            // 更新医生
            doctorService.updateDoctor(selectedDoctor.id, formData)
                .then(() => {
                    setShowModal(false);
                    loadDoctors();
                })
                .catch(err => {
                    setError('更新医生失败');
                    console.error('更新医生失败:', err);
                });
        } else {
            // 创建新医生
            doctorService.createDoctor(formData)
                .then(() => {
                    setShowModal(false);
                    loadDoctors();
                })
                .catch(err => {
                    setError('创建医生失败');
                    console.error('创建医生失败:', err);
                });
        }
    };

    const getDepartmentName = (departmentId) => {
        if (!departments || !Array.isArray(departments)) {
            return '未加载';
        }
        const department = departments.find(dept => dept && dept.id === departmentId);
        return department ? department.name : '未分配';
    };
    
    const getUserName = (userId) => {
        if (!users || !Array.isArray(users)) {
            return '未加载';
        }
        const user = users.find(u => u && u.id === userId);
        return user ? (user.fullName || user.username) : '未知';
    };

    if (loading) {
        return <div className="loading">加载中...</div>;
    }

    if (error) {
        return <div className="error">{error}</div>;
    }

    // 确保有可用的数据
    if (!departments || departments.length === 0) {
        return <div className="error">科室数据加载失败，请刷新页面重试</div>;
    }

    const availableUsers = filterAvailableUsers();

    return (
        <div className="admin-doctor-management">
            <h2>医生管理</h2>
            
            <div className="action-bar">
                <button onClick={handleCreateDoctor} className="add-doctor-btn">添加医生</button>
                <button onClick={() => navigate('/admin/dashboard')} className="back-btn">返回管理面板</button>
            </div>
            
            {doctors.length === 0 ? (
                <p className="no-doctors">暂无医生数据</p>
            ) : (
                <table className="doctors-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>关联用户</th>
                            <th>专业</th>
                            <th>科室</th>
                            <th>执业证号</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {doctors.map(doctor => (
                            <tr key={doctor.id}>
                                <td>{doctor.id}</td>
                                <td>{getUserName(doctor.userId)}</td>
                                <td>{doctor.specialization}</td>
                                <td>{getDepartmentName(doctor.departmentId)}</td>
                                <td>{doctor.licenseNumber}</td>
                                <td>
                                    <button onClick={() => handleEditDoctor(doctor)} className="edit-btn">编辑</button>
                                    <button onClick={() => handleDeleteDoctor(doctor.id)} className="delete-btn">删除</button>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            )}
            
            {showModal && (
                <div className="modal-overlay">
                    <div className="modal-content">
                        <h3>{selectedDoctor ? '编辑医生' : '添加医生'}</h3>
                        <form onSubmit={handleSubmit}>
                            <div className="form-group">
                                <label>用户:</label>
                                {selectedDoctor ? (
                                    <input 
                                        type="text" 
                                        value={getUserName(formData.userId)} 
                                        disabled 
                                    />
                                ) : (
                                    <select 
                                        name="userId" 
                                        value={formData.userId} 
                                        onChange={handleInputChange}
                                        required
                                    >
                                        <option value="">选择用户</option>
                                        {availableUsers.map(user => (
                                            <option key={user.id} value={user.id}>
                                                {user.fullName || user.username}
                                            </option>
                                        ))}
                                    </select>
                                )}
                            </div>
                            
                            <div className="form-group">
                                <label>专业:</label>
                                <input 
                                    type="text" 
                                    name="specialization" 
                                    value={formData.specialization} 
                                    onChange={handleInputChange}
                                    required
                                />
                            </div>
                            
                            <div className="form-group">
                                <label>科室:</label>
                                <select 
                                    name="departmentId" 
                                    value={formData.departmentId} 
                                    onChange={handleInputChange}
                                    required
                                >
                                    <option value="">选择科室</option>
                                    {departments.map(department => (
                                        <option key={department.id} value={department.id}>
                                            {department.name}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            
                            <div className="form-group">
                                <label>执业证号:</label>
                                <input 
                                    type="text" 
                                    name="licenseNumber" 
                                    value={formData.licenseNumber} 
                                    onChange={handleInputChange}
                                    required
                                />
                            </div>
                            
                            <div className="form-group">
                                <label>简介:</label>
                                <textarea 
                                    name="bio" 
                                    value={formData.bio} 
                                    onChange={handleInputChange}
                                    rows="3"
                                ></textarea>
                            </div>
                            
                            <div className="form-group">
                                <label>可预约时间段:</label>
                                <textarea 
                                    name="availableSlots" 
                                    value={formData.availableSlots} 
                                    onChange={handleInputChange}
                                    rows="3"
                                    placeholder="示例: 周一 9:00-12:00,14:00-17:00;周二 9:00-12:00"
                                ></textarea>
                            </div>
                            
                            <div className="form-actions">
                                <button type="submit" className="submit-btn">
                                    {selectedDoctor ? '更新' : '创建'}
                                </button>
                                <button type="button" onClick={() => setShowModal(false)} className="cancel-btn">
                                    取消
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default AdminDoctorManagementPage; 